package com.yylending.las.common.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.yyfax.common.tools.DensityUtil;
import com.yylending.las.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义字符间距的TextView
 * Created by ying_he on 2017/6/14.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class SpacingTextView extends AppCompatTextView {
    int count;
    //记录每个字的二维数组
    float[][] position;
    private String mContent;
    //    private int mWidth;
    private Paint mPaint;
    private float mXSpace;
    private float mTextHeight;
    private int xPaddingMin;

    public SpacingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public void setText(String str) {
        getPositions(str);
        //重新画控件
        this.invalidate();
    }

    public void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SpacingTextView);
        // 设置字间距
        mXSpace = typedArray.getDimension(R.styleable.SpacingTextView_XSpace, DensityUtil.dip2px(context, 6));

        mContent = typedArray.getString(R.styleable.SpacingTextView_strText);
        typedArray.recycle();

        mPaint = new Paint();
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setAntiAlias(true);

        // 设置画笔颜色，也就是字体颜色
        mPaint.setColor(this.getCurrentTextColor());
        mPaint.setTypeface(Typeface.DEFAULT);
        // 设置画笔大小，也就是字体大小
        mPaint.setTextSize(this.getTextSize());
        Paint.FontMetrics fm = mPaint.getFontMetrics();// 得到系统默认字体属性
        // 设置字体高度
        mTextHeight = fm.descent - fm.ascent;
        // 设置比较小的字间距（字母和数字应紧凑）
        xPaddingMin = DensityUtil.dip2px(this.getContext(), 2f);

        getPositions(mContent);
        //重新画控件
        this.invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        setMeasuredDimension(measureWidth(widthMode, width), measureHeight(heightMode, height));
    }

    /**
     * 测量宽度
     *
     * @param mode
     * @param width
     * @return
     */
    private int measureWidth(int mode, int width) {
        int w = 0;
        switch (mode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                w = (int) (mPaint.measureText(mContent) + mXSpace * mContent.length());
                break;
            case MeasureSpec.EXACTLY:
                w = width;
                break;
        }
        return w;
    }

    /**
     * 测量高度
     *
     * @param mode
     * @param height
     * @return
     */
    private int measureHeight(int mode, int height) {
        int h = 0;
        switch (mode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
                h = fontMetrics.bottom - fontMetrics.top;
                break;
            case MeasureSpec.EXACTLY:
                h = height;
                break;
        }
        return h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!TextUtils.isEmpty(mContent)) {
            for (int i = 0; i < count; i++) {
                canvas.drawText(String.valueOf(mContent.charAt(i)), position[i][0], position[i][1], mPaint);
            }
        }
    }


    public void getPositions(String content) {
        this.mContent = content;
        char ch;
        //输入点的 x的坐标
        float x = mXSpace;
        //当前行数
        int lineNum = 1;
        count = content.length();
        //初始化字体位置数组
        position = new float[count][2];
        for (int i = 0; i < count; i++) {
            ch = content.charAt(i);
            String str = String.valueOf(ch);

            //根据画笔获得每一个字符的显示的rect 就是包围框（获得字符宽度）
            Rect rect = new Rect();
            mPaint.getTextBounds(str, 0, 1, rect);
            int strWidth = rect.width();
            //对有些标点做些处理
            if (str.equals("《") || str.equals("（")) {
                strWidth += xPaddingMin * 2;
            }
            //当前行的宽度
            float textWith = strWidth;
            //记录每一个字的位置
            position[i][0] = x;
            position[i][1] = mTextHeight * lineNum;
            //判断是否是数字还是字母 （数字和字母应该紧凑点）
            //每次输入完毕 进入下一个输入位置准备就绪
            if (isNumOrLetters(str)) {
                x += textWith + xPaddingMin;
            } else {
                x += textWith + mXSpace;
            }
        }
        //根据所画的内容设置控件的高度
        setHeight((int) (mTextHeight) * lineNum);
    }


    // 判断是否是字母或者数字
    public boolean isNumOrLetters(String str) {
        String regEx = "^[A-Za-z0-9_]+$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
